package br.edu.udc.sistemas.ia5.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Database {
	
	private static Database database = null;
	
	private Connection connection;
	private String host;
	private String port;
	private String databaseName;
	private String user;
	private String password;
	private String driver;
	private String url;
	
	private Database(){
		this.connection = null;
		this.host = "localhost";
		this.port = "5432";
		this.databaseName = "ia6";
		this.user = "postgres";
		this.password = "postgres";
		this.driver = "org.postgresql.Driver";
		this.url = "jdbc:postgresql"+"://"+this.host+":"+this.port+"/"+this.databaseName;
	}
	
	private static Database getInstance() {
		if (database == null){
			database = new Database();
		}
		return database;
	}
	
	private void connect(){
		try {
			Class.forName(this.driver);
			this.connection = DriverManager.getConnection(this.url, this.user, this.password);
			this.connection.setAutoCommit(false);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	public Connection getConnection() {
		if (this.connection == null){
			this.connect();
		}
		return this.connection;
	}
	
	public boolean isConnected() throws SQLException {
		return (this.connection != null) && (!this.connection.isClosed());
		
	}
	
	public void disconnect() throws SQLException {
		if (this.isConnected()){
			this.connection.close();
		}		
	}
	
	public void commit() throws SQLException{
		if (this.isConnected()){
			this.connection.commit();
		}
	}
	public void rollback() throws SQLException {
		if (this.isConnected()){
			this.connection.rollback();
		}
	}
}
